package com.ybu.oodd.utils.aop;

import com.ybu.oodd.pojo.Result;
import com.ybu.oodd.service.UserService;
import com.ybu.oodd.utils.login.ContextHolder;
import com.ybu.oodd.utils.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Aspect
@Component
@Slf4j
public class Vip {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;

    /**
     * 环绕通知：拦截方法
     */
    @Around("execution(* com.ybu.oodd.controller.JobController.getJobs(..))"
            +"|| execution(* com.ybu.oodd.controller.AIController.AIJL(..))"
    )
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        // vip校验
        Integer userId = ContextHolder.get("userId");
        // 获取 vipList 和 freeNum
        List<Integer> vipList = (List<Integer>) redisUtil.get("vip");
        String freeNumStr = (String) redisUtil.hget("free", userId.toString());
        Integer freeNum = freeNumStr != null ? Integer.valueOf(freeNumStr) : 0;
        log.info("vipList: {}", vipList);
        log.info("freeNum: {}", freeNum);
        // 判断是否为 VIP
        boolean isVip = vipList != null && vipList.contains(userId);
        if (isVip) {
            // 是 VIP，直接放行，不管 freeNum
        }
        // 不是 VIP，看剩余次数
        else if (!isVip && freeNum > 0) {
            // 非 VIP 但还有免费次数：使用一次，放行
            redisUtil.hset("free", userId.toString(), String.valueOf(freeNum - 1));
            userService.downFreeNum(userId);
        } else {
            // 非 VIP 且没有免费次数：拒绝
            return Result.error("498");
        }

        Object result = null;
        try {
            // ✅ 执行原方法
            result = joinPoint.proceed();
            return result;
        } catch (Exception e) {
            // 异常处理
            log.error("方法执行异常：", e);
            throw e; // 继续抛出异常
        }
    }
}